package io.github.lee.repository.qb.di.http.interceptor

import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.net.HttpURLConnection

class QBResponseInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val rawRequest = chain.request()
        val response = chain.proceed(rawRequest)
        var code = response.code
        var msg = when (code) {
            200 -> ""
            400 -> "Bad Request\tThe request was unacceptable, often due to missing a required parameter"
            401 -> "Unauthorized\tInvalid Access Token"
            403 -> "Forbidden\tMissing permissions to perform request"
            404 -> "Not Found\tThe requested resource doesn’t exist"
            500, 503 -> "Something went wrong on our end"
            else -> "Unknown server error"
        }


        val body = response.body
        val data = if (null == body) {
            code = 1000
            msg = "Response body is null or empty"
            ""
        } else {
            body.string()
        }
        val json = if (data.startsWith("[") || data.startsWith("{")) {
            "{\"code\":$code,\"msg\":\"$msg\",\"data\":$data}"
        } else {
            "{\"code\":$code,\"msg\":\"$msg\",\"data\":\"$data\"}"
        }

        return response.newBuilder()
            .body(json.toResponseBody())
            .code(HttpURLConnection.HTTP_OK)
            .build()
    }


}